/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.fragment;

import java.io.Serializable;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.adapter.GiftAdapter;
import com.talben.soudian.adapter.ListBaseAdapter;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.base.BaseListFragment;
import com.talben.soudian.bean.ApkList;
import com.talben.soudian.bean.Gift;
import com.talben.soudian.bean.GiftList;
import com.talben.soudian.ui.EmptyLayout;
import com.talben.soudian.ui.OnTabReselectListener;
import com.talben.soudian.ui.UIHelper;

/**
 * @Title: GiftFragment.java
 * @Package com.talben.soudian.fragment
 * @Description: TODO(添加描述)
 * @author Tal.Ben
 * @date 2015年6月1日 下午3:19:15
 * @version v1.0
 */
public class GiftFragment extends BaseListFragment<Gift> implements
	OnTabReselectListener{

	private static final String CACHE_KEY_PREFIX = "giftlist_";
	
	@Override
	public void onTabReselect() {
		onRefresh();
	}

	@Override
	protected GiftAdapter getListAdapter() {
		return new GiftAdapter();
	}
	
	@Override
    protected String getCacheKeyPrefix() {
        return CACHE_KEY_PREFIX + mCatalog;
    }
	
	@Override
    protected GiftList parseList(JSONArray JArray) throws Exception {
		GiftList list = null;
        try {
            list = new GiftList();
            for (int i = 0; i < JArray.length(); i++) {
            	JSONObject jObj = JArray.getJSONObject(i);
            	Gift gift = new Gift();
            	gift.setServerId(jObj.getString("id"));
            	gift.setScore(jObj.getString("score"));
            	gift.setGicon(jObj.getString("icon"));
            	gift.setDescription(jObj.getString("content"));
            	gift.setType(jObj.getString("type"));
            	gift.setResidue(jObj.getString("count"));
            	gift.setGiftname(jObj.getString("name"));
            	list.getList().add(gift);
			}
        } catch (NullPointerException e) {
            list = new GiftList();
        }
        return list;
    }
	
	@Override
    protected GiftList readList(Serializable seri) {
        return ((GiftList) seri);
    }
	
	@Override
    protected void sendRequestData() {
        SouDianAPI.getGiftList(mCatalog, mCurrentPage, mHandler);
    }
	
	@Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        final Gift gift = mAdapter.getItem(position);
        if (AppContext.getInstance().isLogin()) {
        	if (gift != null) {
            	if (gift.getType().equals("0") || gift.getType().equals("3")) {
            		new AlertDialog.Builder(getActivity())
				     			   .setTitle("确认兑现")
				     			   .setIcon(R.drawable.soudian_icon_48)
				     			   .setMessage(gift.getGiftname())
				     			   .setPositiveButton("确认", 
				     					   new DialogInterface.OnClickListener() {
				     						
				     						@Override
				     						public void onClick(DialogInterface dialog, int which) {
				     	                    	SouDianAPI.cashGift(AppContext.getInstance().getLoginUser().getuPhone(), gift.getServerId(), null, mCashGiftHandler);
				     						}
				     					})
				     				.setNegativeButton("取消", 
				     						new DialogInterface.OnClickListener() {
				     							@Override
				     							public void onClick(DialogInterface dialog, int which) {
				     								AppContext.showToast("已经取消");
				     							}
				     						}).show();	
    			} else {
    				new AlertDialog.Builder(getActivity()).setTitle("提示")
			    				   .setMessage("兑现尚未开通，敬请期待！")
			    				   .setPositiveButton("确定",
			    						new DialogInterface.OnClickListener() {
			    							public void onClick(
			    									DialogInterface dialoginterface,
			    									int i) {
			    								return;
			    							}
			    						}).show();
    			}
            }
		} else {
			new AlertDialog.Builder(getActivity())
			   .setTitle("请先登录")
			   .setIcon(R.drawable.soudian_icon_48)
			   .setMessage("兑现礼品需要登录")
			   .setPositiveButton("确认", 
					   new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							UIHelper.gotoLoginPage(getActivity());
						}
					}).show();
		}
    }
	
	private final AsyncHttpResponseHandler mCashGiftHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideWaitDialog();
			new AlertDialog.Builder(getActivity()).setTitle("获取失败")
							.setMessage("兑现礼品失败,请稍后重试!")
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialoginterface,
												int i) {
											return;
										}
									}).show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				//处理Json
                String result = new String(arg2,"utf-8");
                JSONObject resJObj = new JSONObject(result);
                String title = "";
                if (resJObj.getString("result").equals("false")) {
					title = "获取失败";
				} else {
					title = "兑现结果";
				}
                new AlertDialog.Builder(getActivity()).setTitle(title)
								.setMessage(resJObj.getString("msg"))
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialoginterface,
													int i) {
												return;
											}
										}).show();
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
	
	@Override
    protected void executeOnLoadDataSuccess(List<Gift> data) {
        if (mCatalog == GiftList.CATALOG_ALL) {
            mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            if (mState == STATE_REFRESH)
                mAdapter.clear();
            mAdapter.addData(data);
            mState = STATE_NOMORE;
            mAdapter.setState(ListBaseAdapter.STATE_NO_MORE);
            return;
        }
        super.executeOnLoadDataSuccess(data);
    }
	
	@Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }
	
	@Override
    protected long getAutoRefreshTime() {
        // 最新apk两小时刷新一次
        if (mCatalog == ApkList.CATALOG_ALL) {
            return 2 * 60 * 60;
        }
        return super.getAutoRefreshTime();
    }
	
}

